import urllib
import cv2
from django.conf import settings
import numpy as np
import os
import datetime
#读流文件用于OpenCV识别
def read_image(stream=None, url=None):
    if url is not None:
        response = urllib.request.urlopen(url)
        data_temp = response.read()

    elif stream is not None:
        data_temp = stream.read()

    image = np.asarray(bytearray(data_temp), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image
#binary上传直接转为OpenCV识别
def binary2cv(request):
    bs = request.body
    image = np.asarray(bytearray(bs), dtype="uint8")
    cvImage = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return cvImage

#保存流文件到磁盘
def saveImage(f):
    rootPath = os.path.join(settings.MEDIA_ROOT, datetime.datetime.now().strftime('%Y-%m-%d'))
    if not os.path.exists(rootPath):
        os.makedirs(rootPath, 0o666)
    # filepath = os.path.join(rootPath,f.name)
    filepath = os.path.join(rootPath, datetime.datetime.now().strftime('%H-%M-%S-%f') + ".jpg")
    print(filepath)
    with open(filepath, 'wb') as fp:
        for info in f.chunks():
            fp.write(info)
        fp.close()